<template>
  <div class="CommonSliderBar">
    <div class="CommonSliderBar-top">
      <a-button
        v-if="backHomeBtn"
        icon="home"
        size="large"
        :style="{
          color: btnColor,
          borderColor: btnColor
        }"
        block
        @click="backHome"
      >
        回到首页
      </a-button>

      <a-input-search
        v-if="isSearchHide"
        v-model="searchInputValue"
        style="margin-top: 24px;"
        placeholder="请输入搜索关键字"
        allow-clear
        @search="onInputSearch"
      />
    </div>
    <slot name="top" />
    <div class="CommonSliderBar-container">
      <My-Menu
        :data-list="menu.dataList"
        :selected-keys="menu.selectedKeys"
        :open-keys="menu.openKeys"
        :menu-view-option="itemViewOption"
        @select="selectMenu"
        @openKeys="openKeys"
      />
    </div>

    <div class="CommonSliderBar-foot">
      <a-pagination
        size="small"
        :total="total"
        :current="current"
        :default-page-size="pageSize"
        simple
        @change="pageCurrentChange"
      />
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import { getSystemVariable } from '@/utils/utils';
import MyMenu from './components/menu.vue';
import axios from 'axios';
import _ from 'lodash';
import debounce from 'lodash/debounce';

function getCommonData(focusUrlParams, url) {
  const { method, data, params } = focusUrlParams;
  const requestData = {
    headers: {
      'Token': localStorage.getItem('xcToken')
    },
    url,
    // url: 'http://115.239.175.246:5902/' + url,
    // url: 'http://10.10.10.98:8081' + url,
    method,
    data,
    params
  };
  return axios(requestData);
}

function deepFindItem(json, key, value, res) {
  if (res.value) {
    return res;
  }

  if (Array.isArray(json)) {
    json.forEach(item => deepFindItem(item, key, value, res));
  } else {
    if (json[key] === value) {
      res.value = json;
    } else if (json.children) {
      return deepFindItem(json.children, key, value, res);
    }
  }
}

export default {
  components: { MyMenu },

  props: {
    request: {
      type: Object,
      required: true
    },

    itemViewOption: { // itemTitle: 'title', menuTitle: '有children字段的要显示的属性1', key: '唯一键'
      type: Object,
      required: true
    },

    searchKey: {
      type: String,
      required: true
    },

    searchKeySymbol: {
      type: String,
      default: ''
    },

    autoSelected: {
      type: Boolean,
      default: true
    },

    canSelectNodeFather: {
      type: Boolean,
      default: false
    },
    openMuneChildren: {
      type: Boolean,
      default: true
    },
    // 回到首页按钮显示隐藏
    backHomeBtn: {
      type: Boolean,
      default: true
    },

    isSearchHide: {
      type: Boolean,
      default: true
    },
    // 初始化的搜索值
    inputValue: {
      type: [String, Number],
      default: ''
    }
  },

  data() {
    return {
      btnColor: '#009DFF',
      total: 0,
      current: 1,
      pageSize: 20,
      search: '',
      menu: {
        dataList: [],
        selectedKeys: [],
        openKeys: []
      },
      searchInputValue: ''
    };
  },
  watch: {
    inputValue: {
      handler: function(value) {
        this.searchInputValue = value;
        this.onInputSearch(value);
      }
    }
  },
  created() {
    // 防抖
    this.send = debounce(this.send, 200);
  },
  methods: {
    backHome() {
      this.$router.push('/');
    },

    openKeys(val) {
      this.menu.openKeys = val;
    },

    pageCurrentChange(v) {
      this.current = v;
      this.send();
    },

    send() {
      const { request, search, pageSize } = this;
      const requestData = _.cloneDeep(request);
      this.menu.openKeys = [];
      this.menu.dataList = [];

      if (request.systemVariable && request.systemVariable.length) {
        request.systemVariable.forEach(i => {
          requestData.data[i.key] = getSystemVariable(i.value);
        });
      }
      if (search) {
        if (requestData.type === 2) {
          requestData.data[this.searchKey] = search;
        } else {
          const filterList = requestData.data.filterList || [];
          requestData.data.filterList = filterList.concat([{
            col: this.searchKey,
            value: search,
            symbol: this.searchKeySymbol || undefined
          }]);
        }
      }
      requestData.data.pageSize = requestData.data.pageSize || pageSize;
      requestData.data.pageIndex = this.current - 1;
      getCommonData(requestData, requestData.url).then(
        res => {
          res = res.data;
          if (res.success) {
            const obj = {
              pageIndex: this.current,
              data: res.data
            };
            this.$emit('requestSuccess', obj);
            this.total = res.total;
            if (Array.isArray(res.data) && res.data.length) {
              this.firstClickDefault(res.data);
              this.menu.dataList = res.data;
            } else {
              this.menu.dataList = [];
            }
          } else {
            this.$message.error(res.message);
          }
        },

      ).catch((err) => {
        console.error(err);
        this.$message.error('列表接口调用失败');
      });
    },

    firstClickDefault(data) {
      const itemViewOption = this.itemViewOption;

      const deepNode = data => {
        if (Array.isArray(data) && data.length) {
          deepNode(data[0]);
        } else {
          const c = data.children;
          if (c && c.length) {
            deepNode(c[0]);
            this.menu.openKeys.push(data[this.itemViewOption.key]);
          } else {
            this.$emit('select', {
              key: data[itemViewOption.key],
              value: data
            });
            this.menu.selectedKeys = [data[itemViewOption.key]];
          }
        }
      };

      const firstNode = data => {
        const set = (obj) => {
          this.$emit('fatherSelct', {
            key: obj[itemViewOption.key],
            value: obj
          });
          this.menu.selectedKeys = [obj[itemViewOption.key]];
        };
        Array.isArray(data) && data.length && set(data[0]);
      };
      if (this.autoSelected) {
        this.openMuneChildren ? deepNode(data) : firstNode(data);
      }
    },

    selectMenu(item) {
      this.menu.selectedKeys = [item.key];
      const key = item.key;
      const res = {
        key,
        value: ''
      };

      deepFindItem(this.menu.dataList, this.itemViewOption.key, key, res);
      const evt = item.clickByFather ? 'fatherSelct' : 'select';
      this.$emit(evt, res);
    },

    onInputSearch(v) {
      this.search = v;
      this.current = 1;
      this.send();
    }
  }

};
</script>

<style lang="scss" scoped>
.CommonSliderBar {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .CommonSliderBar-top {
    padding: 24px;
    height: 130px;
  }

  .CommonSliderBar-container {
    flex: 1;
    overflow: auto;
  }

  .CommonSliderBar-foot {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

/deep/ .my_menu_selected {
  color: #1890FF;
}
</style>
